<?php

namespace app\admin\controller\user;

use app\admin\controller\Zlog;
use app\admin\model\org\Orgcate;
use app\common\controller\Backend;
use app\common\logic\OrgLogic;
use fast\Tree;
use think\Config;
use think\Db;
use think\Exception;
use think\Session;

/**
 * 组织结构类别
 *
 * @icon fa fa-circle-o
 */
class Userinput extends Backend
{
    
    /**
     * Orgcate模型对象
     * @var \app\admin\model\org\Orgcate
     */
    protected $model = null;
    protected $orgName_tree = [];
    protected $org_list = [];
    protected $searchFields = 'name,mobile';
    protected $modelValidate = true;
    protected $modelSceneValidate = true;
    protected $current_info = [];
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\org\Orgcate;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign('typeList', model('User')->getTypeList() );
        $this->orgcatelist = $this->model->getOrgCateList();
        $orgGradeModel = new \app\admin\model\org\Orggrade;
        $this->gradeList = $orgGradeModel->getGradeList();
        
        if(ORG_CATE_ID > 0){
            $org_where['parent_id|id'] = ORG_CATE_ID;
        }else{
            $org_where['level'] = array('in', array('1','2'));
        }
        $orgcateList = collection($this->model->where($org_where)->select())->toArray();
        $orgcat = [];
        $parent_ids = [];
        foreach($orgcateList as $k => $v){

            $orgcat[$v['id']] = $v['name'];
            $parent_ids[] = $v['id'];
        }
        $this->orgcat = $orgcat;
        $this->parent_ids = $parent_ids;
        Tree::instance()->init($orgcateList, 'parent_id');
        $this->org_list = $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
        $current = Db::name('org_cate')->where('id','=',ORG_CATE_ID)->find();
        $admin = Db::name('admin')->where('org_cate_id','=',ORG_CATE_ID)->order('id','asc')->limit(1)->select();
        $current['username'] = $admin[0]['username'];
        $current['avatar'] = $admin[0]['avatar'];
        $current['createtime'] = date('Y-m-s', $current['createtime']);
        $orgName_tree = [];
        foreach($result as $k => $v){
            $orgName_tree[$v['id']] = $v['name'];
        }
        $this->orgName_tree = $orgName_tree;
        $this->current_info = $current;
        $this->view->assign('org_cate_id', ORG_CATE_ID);
        $this->view->assign('current', $current);
        $this->view->assign('orgName_tree', $this->orgName_tree);
        $this->view->assign('orgcat', $this->orgcat);

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    public function index(){

        if ($this->request->isAjax()) {
            if($this->request->request('keyField')){
                $data = $this->selectpage2();
                if(empty($data['list'])){
                    $data['list'] = array_merge([['id'=>0,'name'=>'总平台']], $data['list']);
                    $data['total'] = $data['total']+1;
                }
                return json($data);
            }
            if(ORG_CATE_ID > 0){
                $org_where['parent_id'] = ORG_CATE_ID;
                $ids1 = $this->model->where($org_where)->column('id');
                $ids2 = array();
                if($ids1){
                    $ids2 = $this->model->where('parent_id', 'in', $ids1)->column('id');
                }
                $ids = array_unique(array_merge($ids1, $ids2));
                $orgcateList = collection($this->model->where('id', 'in', $ids)->select())->toArray();
            }else{
                $org_where['level'] = array('in', array('1','2','3'));
                $orgcateList = collection($this->model->where($org_where)->select())->toArray();
            }
//            $orgcateList = collection($this->model->where($org_where)->select())->toArray();
            Tree::instance()->init($orgcateList, 'parent_id');
            $list = $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(ORG_CATE_ID));
            $total = count($this->org_list);
            $result = array("total" => $total, "rows" => $list, 'current'=>$this->current_info);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add($ids = null){

        $ids = $this->request->param('ids');
        $this->view->assign("ids", $ids);
        $this->relationSearch = false;
        if($this->request->isPost()){
            $params = $this->request->post("row/a", [], 'strip_tags');
            if($params){
                \think\Db::startTrans();
                try{
                    $validate = new \app\admin\validate\org\Orgcate;
                    if(!$validate->check($params)){
                        $this->error($validate->getError());//内置错误返回
                    }
                    if(isset($params['parent_id']) && $params['parent_id'] > 0){
                        $level = $this->model->where('id', $params['parent_id'])->value('level');
                        $params['level'] = $level+1;
                    }else{
                        $params['parent_id'] = ORG_CATE_ID;
                        $params['level'] = 2;
                    }
                    $params['createtime'] = time();
                    $org_id = $this->model->insertGetId($params);
                    if($org_id === false){
                        \think\Db::rollback();
                        $this->error($this->model->getError());
                    }
//                    if($org_id){
//                        $adminModel = new \app\admin\model\Admin;
//                        $admin_data['org_cate_id'] = $org_id;
//                        $admin_data['username'] = 'org_admin_'.$org_id;
//                        $admin_data['nickname'] = $params['name'];
//                        $password = md5(md5('123456'));
//                        $admin_data['password'] = $password;
//                        $admin_data['avatar'] = '/assets/img/avatar.png';
//                        $admin_id = $adminModel->insertGetId($admin_data);
//                        if($admin_id === false){
//                            \think\Db::rollback();
//                            $this->error($adminModel->getError());
//                        }
//
//                        $authGropuAccessModel = new\app\admin\model\AuthGroupAccess;
//                        $auth_data['uid'] = $admin_id;
//                        $auth_data['group_id'] = 4;
//
//                        $is_success = $authGropuAccessModel->insert($auth_data);
//                        if($is_success === false){
//                            \think\Db::rollback();
//                            $this->error();
//                        }
//                    }
                    
                    \think\Db::commit();

               } catch (Exception $e){
                    \think\Db::rollback();
                    $this->error($e->getMessage());
                }
                
                $this->success();    
            }
            $this->error();
            
        }   

        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row= $this->model->get(['id' => $ids]);
        
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a", [], 'strip_tags');
            if ($params) {
                $result = $row->save($params);
                if ($result === false) {
                    $this->error($row->getError());
                }
                $this->success();
            }
            $this->error();
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 查看家长学员
     */
    public function detail()
    {
        $org_cate_id = $this->request->param('ids');
        $this->view->assign("ids", $org_cate_id);
        //当前是否为关联查询
        $this->relationSearch = true;
        $this->searchFields = 'user.username,user.nickname,user.mobile';
        $this->model = new \app\admin\model\User;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
//            $where2 = $this->getSelfDataWhere('org_cate_id');
            $total = $this->model
                ->with('orggroup')
                ->join('edu_org_grade o', 'o.id = orggroup.org_grade_id','left')
                ->where($where)
//                ->where($where2)
                ->where(['user.org_cate_id'=>$org_cate_id])
                ->where(['user.user_type'=>['in', [0]]])
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->with('orggroup')
                ->join('edu_org_grade o', 'o.id = orggroup.org_grade_id','left')
                ->where($where)
//                ->where($where2)
                ->where(['user.org_cate_id'=>$org_cate_id])
                ->where(['user.user_type'=>['in', [0]]])
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $grade_user_id = [];
            foreach ($list as $k => $v) {
                $v->sort = ($k+1+$offset);
                $v->hidden(['password', 'salt']);
                $list[$k]['org_cate_id'] = isset($this->orgcatelist[$v['org_cate_id']])?$this->orgcatelist[$v['org_cate_id']]:'总平台';
                $grade_user_id[] = $v['id'];
                $v->pwd = '******';
                $v->spwd = '******';
            }
            if($grade_user_id){
                $orgGradeUserModel = model('OrgGradeUser');
                $gradeUserList = $orgGradeUserModel->where(array('user_id' => array('in', $grade_user_id)))->column('org_grade_id', 'user_id');
                foreach($list as $k => $v){
                    $list[$k]['org_grade_id'] = isset($gradeUserList[$v['id']]) ? $gradeUserList[$v['id']]  : 0;
                }
            }
            foreach ($list as $k => $v) {
                $list[$k]['org_grade_name'] = ($v['org_grade_id'] == 0) ? '' : isset($this->gradeList[$v['org_grade_id']])?$this->gradeList[$v['org_grade_id']]:'';
                $list[$k]['pusername'] = Db::name('user')->where('id', $v['parent_id'])->value('username');
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    public function importdialog()
    {
        $org_cate_id = $this->request->param('ids');
        if($org_cate_id <= 0){
            $org_cate_id = ORG_CATE_ID;
        }
        $this->view->assign("ids", $org_cate_id);
        $result = Db::name('org_grade')->where('org_cate_id',$org_cate_id)->select();
        $orgName_tree = [];
        $groupid = 0;
        $i = 0;
        $arr = [
            1=>'幼儿小班',
            2=>'幼儿中班',
            3=>'幼儿大班',
            4=>'一年级',
            5=>'二年级',
            6=>'三年级',
            7=>'四年级',
            8=>'五年级',
            9=>'六年级',
            10=>'初一年级',
            11=>'初二年级',
            12=>'初三年级',
            13=>'高一年级',
            14=>'高二年级',
            15=>'高三年级'];
        foreach($result as $k => $v){
            if(!empty($v['number'])){
                $orgName_tree[$v['id']] = $arr[$v['group']].$v['number'];
                if($i == 0){
                    $groupid = $v['id'];
                }
                $i++;
            }

        }
        $this->view->assign('orgName_tree', $orgName_tree);
        $this->view->assign('groupid', $groupid);
        Session::set('import-gropuid',$groupid);
        return $this->view->fetch();
    }
    /**
     * 导入家长学员
     */
    public function import()
    {
        $this->model = new \app\admin\model\User;
        Config::set('default_return_type', 'json');
        $org_cate_id = $this->request->param('ids');
        $groupid = Session('import-gropuid');
        if($groupid <= 0){
            $this->error('请选择班号！');
        }
        $file= $this->request->file('file');
        $info = $file->getInfo();
        if (!$info) {
            $this->error('请选择要导入的CSV文件');
        }
        $ext = pathinfo($info['name'], PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv'])) {
            $this->error(__('请选择CSV文件'));
        }
        $filename = $info['tmp_name'];
        $file = fopen($filename, 'r');
        $result = $this->model->input_csv($file, $groupid, $org_cate_id);
        fclose($file); //关闭指针
        if (!$result || $result == 0) {
            $this->error('0条，导入失败');
        } else {
            $result = $result * 2;
            $this->success("导入结束，新增". $result."条！");
        }
    }
    public function setsess()
    {
        $gropuid = $this->request->post('gropuid');
        Session::set('import-gropuid',$gropuid);
        $this->success("传参成功");
    }

    /*
     * 添加家长学员
     */
    public function useradd()
    {
        $org_cate_id = $this->request->param('ids');
        $this->view->assign("ids", $org_cate_id);
        $this->model = new \app\admin\model\User;
        if ($this->request->isPost()) {
            $row = $this->request->post("row/a", [], 'strip_tags');
            if ($row) {
                $info['number_id'] = $row['number_id'];
                if(empty($info['number_id'])){
                    $this->error('学号不能为空！');
                }
                $child = (new OrgLogic())->getCateChild(ORG_CATE_ID);
                $total = Db::name('user')->where('number_id', $info['number_id'])->where('org_cate_id','in', $child)->count();
                if($total > 0){
                    $this->error('学号已存在！');
                }
                $info['nickname'] = $row['name'];
                $info['gender'] = $row['gender'];
                $info['age'] = $row['age'];
                $info['username'] = $row['username'];
                if(empty($info['username'])){
                    $this->error('用户名不能为空！');
                }
                $total = Db::name('user')->where('username', $row['username'])->where('org_cate_id','in', $child)->count();
                if($total > 0){
                    $this->error('用户名已存在！');
                }
                $info['password'] = md5(md5($row['password']));
                if(empty($info['password'])){
                    $this->error('密码不能为空！');
                }
                $info['org_cate_id'] = $org_cate_id;
                $info['user_type'] = 0;
                $info['jointime'] = time();
                $info['createtime'] = time();
                $info['status'] = 'normal';

                $parent['username'] = $row['pusername'];
                if(empty($parent['username'])){
                    $this->error('家长用户名不能为空！');
                }
                if($parent['username'] == $info['username']){
                    $this->error('家长用户名和学生用户名不能相同！');
                }
                $total = Db::name('user')->where('username', $parent['username'])->where('org_cate_id','in', $child)->count();
                if($total > 0){
                    $this->error('家长用户名已存在！');
                }
                $parent['password'] = md5(md5($row['ppassword']));
                if(empty($parent['password'])){
                    $this->error('家长密码不能为空！');
                }
                $parent['org_cate_id'] = $org_cate_id;
                $parent['user_type'] = 1;
                $parent['jointime'] = time();
                $parent['createtime'] = time();
                $parent['status'] = 'normal';
                $groupid = $row['groupid'];
                Db::startTrans();
                try {
                    //入库
                    $p_id = Db::name('user')->insertGetId($parent);
                    if($p_id > 0){
                        Db::name('org_grade_user')->insertGetId(['org_grade_id'=>$groupid, 'user_id'=>$p_id]);
                        $info['parent_id'] = $p_id;
                        $id = Db::name('user')->insertGetId($info);
                        if($id > 0){
                            Db::name('org_grade_user')->insertGetId(['org_grade_id'=>$groupid, 'user_id'=>$id]);
                        }
                    }
                    Db::commit();
                    $this->success();
                }catch (Exception $e){
                    Db::rollback();
                    return false;
                }
                $this->error('保存失败！');
            }
            $this->error('缺少必要参数！');
        }
        if($org_cate_id <= 0){
            $org_cate_id = ORG_CATE_ID;
        }
        $this->view->assign("ids", $org_cate_id);
        $result = Db::name('org_grade')->where('org_cate_id',$org_cate_id)->select();
        $orgName_tree = [];
        $i = 0;
        $arr = [
            1=>'幼儿小班',
            2=>'幼儿中班',
            3=>'幼儿大班',
            4=>'一年级',
            5=>'二年级',
            6=>'三年级',
            7=>'四年级',
            8=>'五年级',
            9=>'六年级',
            10=>'初一年级',
            11=>'初二年级',
            12=>'初三年级',
            13=>'高一年级',
            14=>'高二年级',
            15=>'高三年级'];
        foreach($result as $k => $v){
            if(!empty($v['number'])){
                $orgName_tree[$v['id']] = $arr[$v['group']].$v['number'];
                if($i == 0){
                    $groupid = $v['id'];
                }
                $i++;
            }

        }
        $this->view->assign('orgName_tree', $orgName_tree);
        return $this->view->fetch();
    }

    /*
     * 编辑家长学员
     * @param null $ids
     * @return string
     */
    public function useredit($ids = null)
    {
        $this->model = new \app\admin\model\User;
        $row_data = $this->model->get(['id' => $ids]);
        if (!$row_data) {
            $this->error(__('No Results were found'));
        }
        $groupid = Db::name('org_grade_user')->where('user_id', $ids)->value('org_grade_id');
        if ($this->request->isPost()) {
            $row = $this->request->post("row/a", [], 'strip_tags');
            $parent = $this->request->post("parent/a", [], 'strip_tags');
            if ($row) {
                $child = (new OrgLogic())->getCateChild(ORG_CATE_ID);
                $total = Db::name('user')->where('number_id', $row['number_id'])->where('org_cate_id','in', $child)->where('id','<>',$ids)->count();
                if($total > 0){
                    $this->error('学号已存在！');
                }
                $total = Db::name('user')->where('username', $row['username'])->where('org_cate_id','in', $child)->where('id','<>',$ids)->count();
                if($total > 0){
                    $this->error('用户名已存在！');
                }
                $total = Db::name('user')->where('username', $parent['username'])->where('org_cate_id','in', $child)->where('id','<>',$parent['id'])->count();
                if($total > 0){
                    $this->error('家长用户名已存在！');
                }
                $new_grade_id = $row['groupid'];
                unset($row['groupid']);
                if(!empty($row['password'])){
                    $row['password'] = md5(md5($row['password']));
                }
                Db::startTrans();
                try{
                    $result = $row_data->save($row);
                    if ($result === false) {
                        $this->error($row_data->getError());
                    }
                    $third_info = array();
                    $third_info['username'] =$row['username'];
                    $third_info['nickname'] =$row['nickname'];
                    if(!empty($row['password'])){
                        $third_info['password'] =$row['password'];
                    }
                    Db::name('third')->where('u_id', $ids)->where('org_cate_id', ORG_CATE_ID)->update($third_info);
                    if($new_grade_id != 0){
                        if($groupid){
                            if($new_grade_id != $groupid){
                                $grade_user['org_grade_id'] = $new_grade_id;
                                model('OrgGradeUser')->where('user_id', $ids)->where('org_grade_id', $groupid)->update($grade_user);
                                model('OrgGradeUser')->where('user_id', $parent['id'])->where('org_grade_id', $groupid)->update($grade_user);
                            }
                        }else{
                            $grade_user['user_id'] = $ids;
                            $grade_user['org_grade_id'] = $new_grade_id;
                            $pgrade_user['user_id'] = $parent['id'];
                            $pgrade_user['org_grade_id'] = $new_grade_id;
                            model('OrgGradeUser')->insert($grade_user);
                            model('OrgGradeUser')->insert($pgrade_user);
                        }
                    }
                    $data = [];
                    $data['username'] = $parent['username'];
                    if(!empty($parent['password'])){
                        $data['password'] = md5(md5($parent['password']));
                    }
                    Db::name('user')->where('id', $parent['id'])->update($data);
                    $third_pinfo = array();
                    $third_pinfo['username'] =$data['username'];
                    if(!empty($data['password'])){
                        $third_pinfo['password'] =$data['password'];
                    }
                    Db::name('third')->where('u_id', $parent['id'])->where('org_cate_id', ORG_CATE_ID)->update($third_pinfo);
                    Db::commit();
                }catch (Exception $e){
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('操作失败'));
                }
            }
            $this->error('缺少必要参数！');
        }
        $parent = Db::name('user')->where('id', $row_data['parent_id'])->find();
        $this->view->assign("row", $row_data);
        $this->view->assign("parent", $parent);
        $org_cate_id = $row_data->org_cate_id;
        $result = Db::name('org_grade')->where('org_cate_id',$org_cate_id)->select();
        $orgName_tree = [];
        $arr = [
            1=>'幼儿小班',
            2=>'幼儿中班',
            3=>'幼儿大班',
            4=>'一年级',
            5=>'二年级',
            6=>'三年级',
            7=>'四年级',
            8=>'五年级',
            9=>'六年级',
            10=>'初一年级',
            11=>'初二年级',
            12=>'初三年级',
            13=>'高一年级',
            14=>'高二年级',
            15=>'高三年级'];
        foreach($result as $k => $v){
            if(!empty($v['number'])){
                $orgName_tree[$v['id']] = $arr[$v['group']].$v['number'];
            }
        }
        $this->view->assign('orgName_tree', $orgName_tree);
        $this->view->assign('groupid', $groupid);
        return $this->view->fetch();
    }

    /*
     * 删除家长学员
     * @param null $ids
     */
    public function userdel($ids = null)
    {
        $this->model = new \app\admin\model\User;
        if ($ids) {
            Db::startTrans();
            try{
                $p_id = $this->model->where('id', 'in', $ids)->column('parent_id');
                $res = $this->model->where('id', 'in', $ids)->delete();
                if($res===false){
                    $this->error($this->model->getError());
                }
                $this->model->where('id', 'in', $p_id)->delete();
                model('OrgGradeUser')->where('user_id', 'in', $ids)->delete();
                Db::commit();
            }catch (Exception $e){
                Db::rollback();
                $this->error($e->getMessage());
            }

            $this->success();
        }
        $this->error('编号错误！');
    }

    /**
     * 查看教职工
     */
    public function detail2()
    {
        $org_cate_id = $this->request->param('ids');
        $this->view->assign("ids", $org_cate_id);
        //当前是否为关联查询
        $this->relationSearch = true;
        $this->searchFields = 'user.username,user.nickname,user.mobile';
        $this->model = new \app\admin\model\User;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
//            $where2 = $this->getSelfDataWhere('org_cate_id');
            $total = $this->model
                ->with('group')
                ->where($where)
//                ->where($where2)
                ->where(['user.org_cate_id'=>$org_cate_id])
                ->where(['user.user_type'=>3])
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->with('group')
                ->where($where)
//                ->where($where2)
                ->where(['user.org_cate_id'=>$org_cate_id])
                ->where(['user.user_type'=>3])
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            foreach ($list as $k => $v) {
                $v->sort = ($k+1+$offset);
                $v->pwd = '******';
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 导入教职工
     */
    public function import2()
    {
        $this->model = new \app\admin\model\User;
        Config::set('default_return_type', 'json');
        $org_cate_id = $this->request->param('ids');
        $file= $this->request->file('file');
        $info = $file->getInfo();
        if (!$info) {
            $this->error('请选择要导入的CSV文件');
        }
        $ext = pathinfo($info['name'], PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv'])) {
            $this->error(__('请选择CSV文件'));
        }
        $filename = $info['tmp_name'];
        $file = fopen($filename, 'r');
        $result = $this->model->input_csv2($file, $org_cate_id);
        fclose($file); //关闭指针
        if (!$result || $result == 0) {
            $this->error('0条，导入失败');
        } else {
            $this->success("导入结束，新增". $result."条！");
        }
    }
    /*
     * 添加教职工
     */
    public function useradd2()
    {
        $org_cate_id = $this->request->param('ids');
        $this->view->assign("ids", $org_cate_id);
        $this->model = new \app\admin\model\User;
        if ($this->request->isPost()) {
            $row = $this->request->post("row/a", [], 'strip_tags');
            if ($row) {
                if(empty($row['number_id'])){
                    $this->error('工号不能为空！');
                }
                $child = (new OrgLogic())->getCateChild(ORG_CATE_ID);
                $total = Db::name('user')->where('number_id', $row['number_id'])->where('org_cate_id','in', $child)->count();
                if($total > 0){
                    $this->error('工号已存在！');
                }
                if(empty($row['username'])){
                    $this->error('用户名不能为空！');
                }
                $total = Db::name('user')->where('username', $row['username'])->where('org_cate_id','in', $child)->count();
                if($total > 0){
                    $this->error('用户名已存在！');
                }
                $row['password'] = md5(md5($row['password']));
                if(empty($row['password'])){
                    $this->error('密码不能为空！');
                }
                $row['org_cate_id'] = $org_cate_id;
                $row['user_type'] = 3;
                $row['jointime'] = time();
                $row['createtime'] = time();
                $row['status'] = 'normal';

                $id = $this->model->save($row);
                if($id === false){
                    $this->error($this->model->getError());
                }
                $this->success();
            }
            $this->error('缺少必要参数！');
        }
        return $this->view->fetch();
    }

    /*
     * 编辑教职工
     * @param null $ids
     * @return string
     */
    public function useredit2($ids = null)
    {
        $this->model = new \app\admin\model\User;
        $row_data = $this->model->get(['id' => $ids]);
        if (!$row_data) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $row = $this->request->post("row/a", [], 'strip_tags');
            if ($row) {
                $child = (new OrgLogic())->getCateChild(ORG_CATE_ID);
                $total = Db::name('user')->where('number_id', $row['number_id'])->where('org_cate_id','in', $child)->where('id','<>',$ids)->count();
                if($total > 0){
                    $this->error('工号已存在！');
                }
                $child = (new OrgLogic())->getCateChild(ORG_CATE_ID);
                $total = Db::name('user')->where('username', $row['username'])->where('org_cate_id','in', $child)->where('id','<>',$ids)->count();
                if($total > 0){
                    $this->error('用户名已存在！');
                }
                if(!empty($row['password'])){
                    $row['password'] = md5(md5($row['password']));
                }
                Db::startTrans();
                try{
                    $result = $row_data->save($row);
                    if ($result === false) {
                        $this->error($row_data->getError());
                    }
                    $third_info = array();
                    $third_info['username'] =$row['username'];
                    $third_info['nickname'] =$row['nickname'];
                    if(!empty($row['password'])){
                        $third_info['password'] =$row['password'];
                    }
                    Db::name('third')->where('u_id', $ids)->where('org_cate_id', ORG_CATE_ID)->update($third_info);
                    Db::commit();
                }catch (Exception $e){
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success();
            }
            $this->error('缺少必要参数！');
        }
        $this->view->assign("row", $row_data);
        return $this->view->fetch();
    }

    /*
     * 删除教职工
     * @param null $ids
     */
    public function userdel2($ids = null)
    {
        $this->model = new \app\admin\model\User;
        if ($ids) {
            $res = $this->model->where('id', 'in', $ids)->delete();
            if($res===false){
                $this->error($this->model->getError());
            }
            $this->success();
        }
        $this->error('编号错误！');
    }
    /**
     * 搜索下拉列表
     */
    public function searchlist()
    {
        $org_cate_id = $this->request->param('ids');
        if($org_cate_id <= 0){
            $org_cate_id = ORG_CATE_ID;
        }
        $list = Db::name('org_grade')->where('org_cate_id',$org_cate_id)->select();
        $searchlist = [];
        foreach ($list as $key => $value) {
            $searchlist[] = ['id' => $value['id'],'name' => $value['number']];
        }
        $data = ['searchlist' => $searchlist];
        $this->success('', null, $data);
    }
}
